package com.syas.web.controllers;

import com.syas.common.exception.ExcelException;
import com.syas.common.utilities.ExcelUtils;
import com.syas.common.utilities.PageList;
import com.syas.common.utilities.PageListUtil;
import com.syas.model.models.Fmger;
import com.syas.model.models.FrmgerPfmce;
import com.syas.service.interfaces.IFrmgerPfmceService;
import com.syas.service.models.FrmgerPfmceSearch;
import com.syas.web.auth.AuthPassport;
import com.syas.web.models.FrmgerPfmceSearchModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by weigong on 2015/11/30.
 */
@Controller
@RequestMapping(value = "/frmgerPfmce")
public class FrmgerPfmceController extends BaseController{

    @Autowired
    @Qualifier("FrmgerPfmceService")
    private IFrmgerPfmceService frmgerPfmceService;


    @AuthPassport
    @RequestMapping(value="/frmgerPfmcePage", method = {RequestMethod.GET})
    public String frmgerPfmcePage(HttpServletRequest request, Model model, FrmgerPfmceSearchModel searchModel){
        model.addAttribute("requestUrl", request.getServletPath());
        model.addAttribute("requestQuery", request.getQueryString());
        model.addAttribute("searchModel", searchModel);
        searchModel.setPage(ServletRequestUtils.getIntParameter(request, PageListUtil.PAGE_NO_NAME, PageListUtil.DEFAULT_PAGE_NO));
        searchModel.setPageSize(ServletRequestUtils.getIntParameter(request, PageListUtil.PAGE_SIZE_NAME, PageListUtil.DEFAULT_PAGE_SIZE));
        PageList<FrmgerPfmceSearch> list = frmgerPfmceService.listFrmgerPfmcePage(searchModel);
        model.addAttribute("contentModel", list);
        return "/orgfrmger/frmgerPfmceList";
    }




    @RequestMapping(value="/addFrmgerPfmcerByExcel",method = {RequestMethod.POST})
    public void addFrmgerPfmcerByExcel(HttpServletRequest request,HttpServletResponse response) throws IOException {

        String resultMsg  = "";
        //获取上传文件的
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        String suffix = "";
        if(!file.isEmpty()){
            List<FrmgerPfmce> list = new ArrayList<FrmgerPfmce>();
            suffix =  file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            LinkedHashMap<String,String> hashMap = new LinkedHashMap<String,String>();
            toHashMap(hashMap);
            try {
            if(".xls".equals(suffix)){
                list = ExcelUtils.excelToList(file.getInputStream(), "Sheet1",FrmgerPfmce.class,hashMap);
            }else if((".xlsx").equals(suffix)){
                list = ExcelUtils.excelToListByXSSF(file.getInputStream(), "Sheet1", FrmgerPfmce.class, hashMap, 25);
            }else{
                resultMsg = "文件格式不正确";
            }
            } catch (ExcelException e) {
                e.printStackTrace();
                resultMsg = "导入失败";
                return;
            }
            //持久化操作
            boolean bo = frmgerPfmceService.addFrmgerPfmceByExcel(list);
            if(bo){
                resultMsg = "导入成功";
            }else{
                resultMsg = "导入失败";
            }
        }else {
            resultMsg = "文件获取失败";
        }
        responseWrite(response,"{\"result\":\""+resultMsg+"\"}");
    }

    /**
     * 响应文件上传
     * @param response
     * @param data
     */
    public void responseWrite(HttpServletResponse response,String data){
        response.setContentType("text/html; charset=utf-8");
        try {
            response.getWriter().write(data);
        }  catch (IOException e) {
        }
    }


    /**
     * 保存文件
     * @param stream
     * @param path
     * @param savefile
     * @throws IOException
     */
    public void saveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException {
        FileOutputStream fs = new FileOutputStream(path + "/" + savefile);

        byte[] buffer = new byte[1024 * 1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }



    /**
     * @param hashMap ：excel表头和字段属性名字的hashmap集合
     * @return
     * @MethodName : toHashMap
     * @Description : excel表头和字段属性名字的hashmap集合
     */
    private void toHashMap(LinkedHashMap<String,String> hashMap){
        hashMap.put("客户姓名","customerNname");
        hashMap.put("客户e租宝账户名","customerCmerEzbo");
        hashMap.put("总公司","headOffice");
        hashMap.put("分公司编号","branchNumber");
        hashMap.put("所属区域","area");
        hashMap.put("区域负责人","arealeader");
        hashMap.put("所属分公司","subordinateBranch");
        hashMap.put("分公司负责人","brchcomyleader");
        hashMap.put("所属营业部","salesDepartment");
        hashMap.put("营业部负责人","saledeptleader");
        hashMap.put("所属分部","subBranch");
        hashMap.put("分部负责人","diviseleader");
        hashMap.put("所属团队","subTeam");
        hashMap.put("团队负责人","teamleader");
        hashMap.put("理财师姓名","financialPlannerName");
        hashMap.put("理财师e租宝账户名","financialPlannerCmerEzbo");
        hashMap.put("投资产品","investpdt");
        hashMap.put("投资金额（元）","investamt");
        hashMap.put("绩效业绩","achieve");
        hashMap.put("投资时间","investtime");
        hashMap.put("投资方式（线上/线下）","investway");
        hashMap.put("有效天数","effeday");
        hashMap.put("赎回时间","redetime");
        hashMap.put("投资ID","investid");
    }



    }
